<template>
  <div class="main">
    <div v-if="!inApp" class="detialTitle">
      <h1 class="tc">{{ article.articleName }}</h1>
      <p class="tc"><span>作者：{{ article.createBy }} &nbsp;&nbsp;日期:{{ article.createTime }} </span></p>
    </div>
    <div v-if="!inApp && ((inWechat() && isLogin) || (!inWechat()))" style="margin:15px;">
      <van-button style="margin-top: 30px;margin-bottom:15px;" block type="primary" @click="open">下载APP打开查看</van-button>
    </div>
    <div v-if="!inApp" class="ls-fengcai summary" v-html="summary" />
    <div v-if="inApp" class="ls-fengcai" v-html="content" />
    <div v-if="!isLogin && inWechat()" style="margin:15px;">
      <van-button block type="primary" @click="login">登录</van-button>
    </div>
    <div v-if="!inApp && ((inWechat() && isLogin) || (!inWechat()))" style="margin:15px;">
      <van-button style="margin-top: 30px;" block type="primary" @click="open">下载APP打开查看</van-button>
    </div>
    <div v-if="!inApp && isLogin" style="margin:15px;">
      <van-button style="margin-top: 30px;" block type="primary" @click="openLogout">退出登录</van-button>
    </div>
    <div v-show="showGuide" class="zhezhao" />
  </div>
</template>

<script>
import { getArticle } from '@/api/system/article'
import keywordCrud from '@/api/system/keyword'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
  name: 'ShareArticle',
  data: () => {
    return {
      title: '',
      article: {},
      showGuide: false,
      keywords: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    isLogin() {
      return getToken()
    },
    inApp() {
      return this.$route.query.app
    },
    content() {
      if ((this.inApp || this.isLogin) && this.article && this.article.content && this.article.content.length > 0) {
        let data = this.article.content.replace(/<img[^>]*>/gi, function(match, capture) {
          return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/gi, '').replace('<img ', '<img style="max-width:100%;height:auto;" ') // 替换style
        })
        data = data.replaceAll('<b></b>', '').replaceAll('</b><b>', '')
        if (this.keywords) {
          for (const keyword of this.keywords) {
            data = data.replaceAll(keyword.keyword, `<a href="${keyword.value}" style="color: #277de2;text-decoration: underline;" target="_blank">${keyword.keyword}</a>`)
          }
        }
        return data
      }
      return null
    },
    summary() {
      return this.article && this.article.summary && this.article.summary.length > 0 ? this.article.summary.replaceAll(' ', '&nbsp;').replaceAll('\n', '<br />') : null
    }
  },
  mounted() {
    const user = this.$store.getters.user
    if (this.isLogin && user && this.$route.query.pid && this.$route.query.pid.length > 0) {
      // 当前用户的没有上级或者
      const fixedParent = user.appLoginTime && user.pid
      if (!fixedParent && user.pid !== parseInt(this.$route.query.pid)) {
        // 重新登录
        this.logout()
      }
    }
    keywordCrud.getKeywords({ page: 0, size: 999, sort: 'createTime,desc' }).then(result => {
      this.keywords = result.content
      getArticle(this.$route.query.id).then(res => {
        this.article = res
      })
    })
    setTimeout(() => {
      if (!this.inApp && !this.inWechat()) {
        this.open()
      }
    }, 2000)
  },
  methods: {
    login() {
      this.$router.push(`/phone-login?redirect=${this.$route.fullPath}`) // 否则全部重定向到登录页
    },
    open() {
      var is_weixin = navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
      if (is_weixin) {
        this.showGuide = is_weixin
      } else {
        this.openApp('lawquery://article?id=' + this.$route.query.id + '&pid=' + this.$route.query.pid, () => {
          this.downloadApp()
          this.$message.success('正在为您下载问易得应用，请于下载完成后安装打开应用查看文章')
        })
      }
    },
    openLogout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout()
      })
    },
    logout() {
      this.$store.dispatch('LogOut').then(() => {
        location.reload()
      })
    },
    inWechat() {
      console.log(navigator.userAgent.toLowerCase())
      return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
    },
    /**
    * 唤起app
    * @param {any} uri  app schema
    * @param {any} fallback  唤起失败回调
    */
    openApp(uri, fallback) {
      const ifr = document.createElement('iframe')
      ifr.src = uri
      ifr.style.display = 'none'
      if (fallback) {
        this.checkOpen((opened) => {
          if (!opened) {
            fallback()
          }
        })
      }
      document.body.appendChild(ifr)
      setTimeout(() => {
        document.body.removeChild(ifr)
      }, 2000)
    },
    downloadApp() {
      // 判断是Android还是iOS
      const u = navigator.userAgent
      let system = ''
      if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
        system = 'Android'
      } else if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        system = 'iOS'
      } else {
        system = 'unknown'
      }
      // 根据系统不同，跳转不同的下载APP地址
      if (system === 'Android') {
        window.location = 'https://www.wenyide.com/file/apk/app-release.apk'
      } else if (system === 'iOS') {
        window.location = 'https://apps.apple.com/cn/app/%E9%97%AE%E6%98%93%E5%BE%97%E6%B3%95%E5%BE%8B%E5%92%A8%E8%AF%A2/id1636311536'
      }
    },
    // 检查app是否打开
    checkOpen(cb) {
      const clickTime = +(new Date())
      function check(elsTime) {
        if (elsTime > 3000 || document.hidden || document.webkitHidden) {
          cb(true)
        } else {
          cb(false)
        }
      }
      // 启动间隔20ms运行的定时器，并检测累计消耗时间是否超过3000ms，超过则结束
      let count = 0
      let intHandle = null
      intHandle = setInterval(() => {
        count++
        const elsTime = +(new Date()) - clickTime
        if (count >= 100 || elsTime > 3000) {
          clearInterval(intHandle)
          check(elsTime)
        }
      }, 20)
    }
  }
}
</script>

<style lang="scss" scoped>
*{margin:0;padding:0;}

ul,ol,li{list-style-type:none;}
li{ vertical-align:top;}
em,i{font-style:normal;}
.dib{display:block;}       .din{display:none;}        .dii{display:inline;}
.fa{font-family:arial;}    .ft{font-family:tahoma;}   .fw{font-family:"Microsoft YaHei"}    .fs{font-family:"SimSun"}
.fl{float:left;}        .fr{float:right;}
.f12{font-size:12px;}   .f14{font-size:14px;}   .f16{font-size:16px;}
.fb{font-weight:bold;}  .fb16{font-weight:bold; font-size:16px;} .fb14{font-weight:bold; font-size:14px;}
.tc{text-align:center;}    .tl{text-align:left;}    .tr{text-align:right;}
.main {width:100%; height: 100%; position:relative;}
img {border:none; vertical-align:middle;max-width: 100%;}
.detialTitle {
  border-bottom: #ccc solid 1px;
  padding-top: 5px;
  h1 {
    font-size: 20px;
    padding: 10px 0;
    font-weight: normal;
  }
  p {
    color: #999;
    font-size: 14px;
    span {
      padding-right: 10px;
      font-size: 12px;
    }

  }

}
/*文章*/
.summary {
  border: 1px solid #999;
  border-radius: 8px;
  margin: 10px 15px;
}
.ls-fengcai {
  padding: 10px;
  font-size: 16px;
  line-height: 30px;
  .show-cont {
    img {
      border:none; vertical-align:middle;max-width: 100%;
    }
  }

  a {
    color: #277de2;
    text-decoration: underline;
  }
  li {
    float: left;
    width: 46%;
    padding-left: 2%;
    padding-right: 2%;
    margin-bottom: 10px;
    a {
      display: block;
      box-shadow: 1px 2px 2px #ccc;
    }
  }
  p {
    line-height: 28px;
    margin-bottom: 5px;
    a {
      font-size: 16px;
    }
    img {
      border:none; vertical-align:middle;max-width: 100%;
    }
  }
  .thumb {
    width: 100%;
    padding: 10px 0px;
    img {
      display: block;
      width: 80%;
      margin: 0 0;
    }
  }
}
.zhezhao{
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: url("../../../assets/images/bgzz.png") center center;
  background-size: 100%;
  position: fixed;
  top:0;
  bottom: 0;
  left:0;
  right: 0;
}

</style>
